/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Ventanas.Administracion;

import com.asistencia.DAO.factory.FactoryDAO;
import com.asistencia.model.Funcionario;
import com.asistencia.model.Perfil;
import java.util.ArrayList;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

/**
 *
 * @author rfarias
 */
public class FuncionariosADD extends javax.swing.JFrame {
    int flag;

    /**
     * Creates new form FuncionariosADD
     */
    public FuncionariosADD() {
        initComponents();
        llenaCombo();

        flag=0;

    }

    public FuncionariosADD(Funcionario fun) {
        initComponents();
        llenaCombo();
        this.txtRut.setText(fun.getRut_funcionario());
        this.txtNombre.setText(fun.getNombres());
        this.txtCorreo.setText(fun.getCorreo());
        this.txtRuta.setText(fun.getRuta());
        this.txtPass.setText(fun.getPassword());
        this.cmbPerfil.setSelectedItem(fun.getPerfil());

        flag=1;
    }

     /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        txtRut = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtCorreo = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txtPass = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        btnGuardar = new javax.swing.JButton();
        btnVolver = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        txtRuta = new javax.swing.JTextField();
        cmbPerfil = new javax.swing.JComboBox();
        jLabel7 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("SITA - Administración");
        setBounds(new java.awt.Rectangle(200, 200, 0, 0));
        setIconImage(new ImageIcon(getClass().getResource("/Ventanas/icono.png")).getImage());

        jLabel1.setText("Rut");

        jLabel2.setText("Nombre");

        jLabel3.setText("Correo");

        jLabel4.setText("Clave");

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel5.setText("Agregar Funcionario");

        btnGuardar.setText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        btnVolver.setText("Volver");
        btnVolver.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVolverActionPerformed(evt);
            }
        });

        jLabel6.setText("Ruta");

        cmbPerfil.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel7.setText("Perfil");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(txtRut)
                    .addComponent(txtNombre)
                    .addComponent(txtCorreo)
                    .addComponent(txtPass)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnVolver, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel6)
                    .addComponent(txtRuta)
                    .addComponent(jLabel7)
                    .addComponent(cmbPerfil, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel5)
                .addGap(18, 18, 18)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtRut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtCorreo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtRuta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cmbPerfil, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnVolver)
                    .addComponent(btnGuardar))
                .addGap(40, 40, 40))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnVolverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVolverActionPerformed

        this.dispose();

    }//GEN-LAST:event_btnVolverActionPerformed

    private void llenaCombo()
    {
        DefaultComboBoxModel value =new DefaultComboBoxModel();
        ArrayList<Perfil> per;
        this.cmbPerfil.setModel(value);
        per = (ArrayList<Perfil>) FactoryDAO.getInstance().getDataPer().findAll();

        for (Perfil p : per)
        {
        value.addElement(p);
        }

    }
/**
 * Al presionar Botón Guardar (btnGuardar):
 * 1. Se crea una instancia de la clase Funcionario (fn)
 * 2. El objeto fn es llenado con el contenido de los cuadros de texto(rut, nombre, correo, ruta, clave y perfil)
 * 3. Si la variable int flag(indica si el funcionario a ingresar es nuevo) es cero, se llama al método searchById(recibe como parámetro el rut del objeto fn) de la clase FuncionarioDAO preguntando si es vacío
 * 4. De ser vacío se llama al método insert de la clase FuncionarioDAO(recibe como parámetro el objeto fn)
 * 5. Se muestra ventana con mensaje de Funcionario creado.
 * 6. En caso contrario muestra mensaje de error al ingresar el funcionario.
 * 7. 
 * @param evt 
 */
    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed

        Funcionario fn = new Funcionario (this.txtRut.getText(),this.txtNombre.getText(),this.txtCorreo.getText(),this.txtRuta.getText(),this.txtPass.getText(),(Perfil) this.cmbPerfil.getSelectedItem());

        if (flag==0)
        {
                if (FactoryDAO.getInstance().getDataFun().searchById(fn.getRut_funcionario())==null)
                {
                    if (FactoryDAO.getInstance().getDataFun().insert(fn)!= null)
                    {
                       JOptionPane.showMessageDialog(rootPane, "Se ha Creado con exito al funcionario "+fn.getNombres(), "Creacion Exitosa" , JOptionPane.INFORMATION_MESSAGE );
                    }
                    else
                    {
                       JOptionPane.showMessageDialog(rootPane, "Ha ocurrido un error no especificado en el sistema.\n Por favor, contacte al administrador", "ERROR" , JOptionPane.ERROR_MESSAGE );
                    }
                }
                else
                {
                    JOptionPane.showMessageDialog(rootPane, "El Rut que intenta ingresar ya existe en el sistema", "ERROR" , JOptionPane.ERROR_MESSAGE );
                }
        }

        if (flag==1)
        {
                if (FactoryDAO.getInstance().getDataFun().searchById(fn.getRut_funcionario())==null)
                {
                     JOptionPane.showMessageDialog(rootPane, "No se puede modificar el rut de un Funcionario ya ingresado", "ERROR" , JOptionPane.ERROR_MESSAGE );
                }
                else
                {

                    if (FactoryDAO.getInstance().getDataFun().update(fn)!= null)
                    {
                       JOptionPane.showMessageDialog(rootPane, "Se han actualizado los datos de "+fn.getNombres(), "Actualización Exitosa" , JOptionPane.INFORMATION_MESSAGE );
                    }
                    else
                    {
                       JOptionPane.showMessageDialog(rootPane, "Ha ocurrido un error no especificado en el sistema.\n Por favor, contacte al administrador", "ERROR" , JOptionPane.ERROR_MESSAGE );
                    }

                }
        }

    }//GEN-LAST:event_btnGuardarActionPerformed
// <editor-fold defaultstate="collapsed" desc="Estandar">
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FuncionariosADD.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FuncionariosADD.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FuncionariosADD.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FuncionariosADD.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FuncionariosADD().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnVolver;
    private javax.swing.JComboBox cmbPerfil;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JTextField txtCorreo;
    private javax.swing.JTextField txtNombre;
    private javax.swing.JTextField txtPass;
    private javax.swing.JTextField txtRut;
    private javax.swing.JTextField txtRuta;
    // End of variables declaration//GEN-END:variables
// </editor-fold>
}
